package com.ray.business.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ray.business.builder.OrderStepBuilder;
import com.ray.business.builder.OrderStepVOBuilder;
import com.ray.business.check.OrderStepCheck;
import com.ray.business.service.ProdOrderStepService;
import com.ray.business.service.ProdStepService;
import com.ray.business.table.dto.OrderStepQueryDTO;
import com.ray.business.table.entity.ProdOrderStep;
import com.ray.business.table.entity.ProdStep;
import com.ray.business.table.params.order.step.OrderStepCreateParams;
import com.ray.business.table.params.order.step.OrderStepEditParams;
import com.ray.business.table.params.order.step.OrderStepQueryParams;
import com.ray.business.table.vo.OrderStepVO;
import com.ray.common.SysMsgCodeConstant;
import com.ray.system.builder.CommonPageBuilder;
import com.ray.validate.support.utils.ValidateUtil;
import com.ray.wms.check.WarehouseCheck;
import com.ray.wms.service.WmsWarehouseService;
import com.ray.wms.table.entity.WmsWarehouse;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.enums.YesOrNoEnum;
import com.ray.woodencreate.exception.BusinessExceptionFactory;
import com.ray.woodencreate.page.CommonPage;
import com.ray.woodencreate.result.MsgCodeConstant;
import com.ray.woodencreate.result.Result;
import com.ray.woodencreate.result.ResultFactory;
import com.ray.woodencreate.util.Assert;
import com.ray.woodencreate.util.LogInUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author bo shen
 * @Description: 订单工序相关服务
 * @Class: OrderStepApi
 * @Package com.ray.base.api
 * @date 2020/5/27 11:15
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Service
@Slf4j
public class OrderStepApi {

    @Autowired
    private ProdOrderStepService prodOrderStepService;
    @Autowired
    private WmsWarehouseService wmsWarehouseService;
    @Autowired
    private ProdStepService prodStepService;


    /**
     * 查询订单工序列表信息 分页  非删除的
     *
     * @param queryParams
     * @return
     */
    public Result<IPage<OrderStepVO>> pageOrderSteps(CommonPage<OrderStepQueryParams, Page<OrderStepVO>> queryParams) {
        Assert.notNull(queryParams, "参数[queryParams]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        Map<String, WmsWarehouse> wmsWarehouseMap = new HashMap<>();
        Map<String, ProdStep> stepMap = new HashMap<>();
        CommonPageBuilder<OrderStepQueryDTO, ProdOrderStep> commonPageBuilder = new CommonPageBuilder<>(OrderStepQueryDTO.class);
        commonPageBuilder.appendEntity(queryParams.getEntity()).appendQuery(queryParams.getQuery()).appendPage(queryParams.getPage());
        IPage<ProdOrderStep> page = prodOrderStepService.page(commonPageBuilder.bulid(), loginUser);
        List<ProdOrderStep> orders = page.getRecords();
        //结果对象
        IPage<OrderStepVO> pageList = new Page<>();
        pageList.setTotal(page.getTotal());
        pageList.setCurrent(page.getCurrent());
        pageList.setSize(page.getSize());
        //查询到结果 数据转换
        if (ObjectUtil.isNotNull(orders)) {
            pageList.setRecords(orders.stream().map(sysOrderStep -> {
                OrderStepVOBuilder orderStepBuilder = new OrderStepVOBuilder();
                orderStepBuilder.append(sysOrderStep);

                ProdStep step = stepMap.get(sysOrderStep.getStepCode());
                if (ObjectUtil.isNull(step)) {
                    step = prodStepService.queryStepByStepCode(sysOrderStep.getStepCode(), loginUser);
                    stepMap.put(sysOrderStep.getStepCode(), step);
                }
                orderStepBuilder.append(step);
                //查询仓库信息
                WmsWarehouse inWarehouse = wmsWarehouseMap.get(sysOrderStep.getInWarehouseCode());
                if (ObjectUtil.isEmpty(inWarehouse)) {
                    inWarehouse = wmsWarehouseService.queryWarehouseByWarehouseCode(sysOrderStep.getInWarehouseCode(), loginUser);
                    wmsWarehouseMap.put(inWarehouse.getWarehouseCode(), inWarehouse);
                }
                orderStepBuilder.appendIn(inWarehouse);
                WmsWarehouse outWarehouse = wmsWarehouseMap.get(sysOrderStep.getOutWarehouseCode());
                if (ObjectUtil.isEmpty(outWarehouse)) {
                    outWarehouse = wmsWarehouseService.queryWarehouseByWarehouseCode(sysOrderStep.getOutWarehouseCode(), loginUser);
                    wmsWarehouseMap.put(outWarehouse.getWarehouseCode(), outWarehouse);
                }
                orderStepBuilder.appendOut(outWarehouse);
                return orderStepBuilder.bulid();
            }).collect(Collectors.toList()));
        } else {
            pageList.setRecords(new ArrayList<>());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, pageList);
    }

    /**
     * 查询订单工序列表信息--启用的订单工序
     *
     * @param queryParams
     * @return
     */
    public Result<List<OrderStepVO>> queryOrderSteps(OrderStepQueryParams queryParams) {
        Assert.notNull(queryParams, "参数[queryParams]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        Map<String, WmsWarehouse> wmsWarehouseMap = new HashMap<>();
        Map<String, ProdStep> stepMap = new HashMap<>();
        OrderStepQueryDTO queryDTO = new OrderStepQueryDTO();
        BeanUtil.copyProperties(queryParams, queryDTO);
        queryDTO.setStatus(YesOrNoEnum.YES.getValue());
        List<ProdOrderStep> orders = prodOrderStepService.list(queryDTO, loginUser);
        //查询对象
        List<OrderStepVO> list = new ArrayList<>();
        if (ObjectUtil.isNotNull(orders)) {
            list = orders.stream().map(sysOrderStep -> {
                OrderStepVOBuilder orderStepBuilder = new OrderStepVOBuilder();
                orderStepBuilder.append(sysOrderStep);
                ProdStep step = stepMap.get(sysOrderStep.getStepCode());
                if (ObjectUtil.isNull(step)) {
                    step = prodStepService.queryStepByStepCode(sysOrderStep.getStepCode(), loginUser);
                    stepMap.put(sysOrderStep.getStepCode(), step);
                }
                orderStepBuilder.append(step);
                //查询仓库信息
                WmsWarehouse inWarehouse = wmsWarehouseMap.get(sysOrderStep.getInWarehouseCode());
                if (ObjectUtil.isEmpty(inWarehouse)) {
                    inWarehouse = wmsWarehouseService.queryWarehouseByWarehouseCode(sysOrderStep.getInWarehouseCode(), loginUser);
                    wmsWarehouseMap.put(inWarehouse.getWarehouseCode(), inWarehouse);
                }
                orderStepBuilder.appendIn(inWarehouse);
                WmsWarehouse outWarehouse = wmsWarehouseMap.get(sysOrderStep.getOutWarehouseCode());
                if (ObjectUtil.isEmpty(outWarehouse)) {
                    outWarehouse = wmsWarehouseService.queryWarehouseByWarehouseCode(sysOrderStep.getOutWarehouseCode(), loginUser);
                    wmsWarehouseMap.put(outWarehouse.getWarehouseCode(), outWarehouse);
                }
                orderStepBuilder.appendOut(outWarehouse);
                return orderStepBuilder.bulid();
            }).collect(Collectors.toList());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, list);
    }


    /**
     * 创建订单工序
     *
     * @param createParams 创建对象
     * @return Result
     */
    @Transactional
    public Result<String> createOrderStep(OrderStepCreateParams createParams) {
        ValidateUtil.validate(createParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //查询仓库数据
        WmsWarehouse inWarehouse = wmsWarehouseService.queryWarehouseByWarehouseCode(createParams.getInWarehouseCode(), loginUser);
        new WarehouseCheck(inWarehouse).checkNull("入库仓库不存在");
        //查询仓库数据
        WmsWarehouse outWarehouse = wmsWarehouseService.queryWarehouseByWarehouseCode(createParams.getOutWarehouseCode(), loginUser);
        new WarehouseCheck(outWarehouse).checkNull("出库仓库不存在");
        ProdOrderStep prodOrderStep = prodOrderStepService.queryOrderStepByIndexSort(createParams.getOrderNo(), createParams.getIndexSort(), loginUser);
        new OrderStepCheck(prodOrderStep).checkSame(null, "订单工序顺序已经存在");
        ProdOrderStep orderStep = prodOrderStepService.queryOrderStepByStepCode(createParams.getOrderNo(), createParams.getStepCode(), loginUser);
        new OrderStepCheck(orderStep).checkSame(null, "订单工序已经存在");
        OrderStepBuilder orderBuilder = new OrderStepBuilder();
        orderBuilder.append(createParams).appendStatus(YesOrNoEnum.YES.getValue()).appendCreate(loginUser);
        //保存订单信息
        if (!prodOrderStepService.save(orderBuilder.bulid())) {
            log.info("保存订单工序接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException("保存订单工序失败");
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, orderBuilder.getCode());
    }

    /**
     * 编辑订单工序
     *
     * @param editParams 编辑对象
     * @return Result
     */
    @Transactional
    public Result<String> editOrderStep(OrderStepEditParams editParams) {
        ValidateUtil.validate(editParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        ProdOrderStep sysOrderStep = prodOrderStepService.queryOrderStepByOrderStepCode(editParams.getCode(), loginUser);
        new OrderStepCheck(sysOrderStep).checkNull("订单工序不存在");
        //查询仓库数据
        WmsWarehouse inWarehouse = wmsWarehouseService.queryWarehouseByWarehouseCode(editParams.getInWarehouseCode(), loginUser);
        new WarehouseCheck(inWarehouse).checkNull("入库仓库不存在");
        //查询仓库数据
        WmsWarehouse outWarehouse = wmsWarehouseService.queryWarehouseByWarehouseCode(editParams.getOutWarehouseCode(), loginUser);
        new WarehouseCheck(outWarehouse).checkNull("出库仓库不存在");
        ProdOrderStep prodOrderStep = prodOrderStepService.queryOrderStepByIndexSort(sysOrderStep.getOrderNo(), editParams.getIndexSort(), loginUser);
        new OrderStepCheck(prodOrderStep).checkSame(editParams.getCode(), "订单工序顺序已经存在");
        ProdOrderStep orderStep = prodOrderStepService.queryOrderStepByStepCode(sysOrderStep.getOrderNo(), editParams.getStepCode(), loginUser);
        new OrderStepCheck(orderStep).checkSame(editParams.getCode(), "订单工序已经存在");
        OrderStepBuilder orderBuilder = new OrderStepBuilder();
        orderBuilder.append(editParams).appendEdit(loginUser);
        //编辑订单信息
        if (!prodOrderStepService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("编辑订单工序接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException("订单工序编辑异常");
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, orderBuilder.getCode());
    }


    /**
     * 删除订单工序
     *
     * @param code 订单工序编码
     * @return Result
     */
    @Transactional
    public Result<String> deleteOrderStep(String code) {
        ValidateUtil.hasLength(code, "参数[code]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        ProdOrderStep sysOrderStep = prodOrderStepService.queryOrderStepByOrderStepCode(code, loginUser);
        new OrderStepCheck(sysOrderStep).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        OrderStepBuilder orderBuilder = new OrderStepBuilder();
        orderBuilder.appendCode(code).appendEdit(loginUser).delete();
        //删除订单信息
        if (!prodOrderStepService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("删除订单工序接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException("删除订单工序异常");
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, orderBuilder.getCode());
    }

    /**
     * 开启订单工序
     *
     * @param code 订单编码工序
     * @return Result
     */
    @Transactional
    public Result<String> openOrderStep(String code) {
        ValidateUtil.hasLength(code, "参数[code]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        ProdOrderStep sysOrderStep = prodOrderStepService.queryOrderStepByOrderStepCode(code, loginUser);
        new OrderStepCheck(sysOrderStep).checkNull("订单工序不存在");
        OrderStepBuilder orderBuilder = new OrderStepBuilder();
        orderBuilder.appendCode(code).appendEdit(loginUser).open();
        //开启订单信息
        if (!prodOrderStepService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("开启订单工序接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException("开启订单工序异常");
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, orderBuilder.getCode());
    }

    /**
     * 关闭订单工序
     *
     * @param code 订单工序编码
     * @return Result
     */
    @Transactional
    public Result<String> closeOrderStep(String code) {
        ValidateUtil.hasLength(code, "参数[code]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        ProdOrderStep sysOrderStep = prodOrderStepService.queryOrderStepByOrderStepCode(code, loginUser);
        new OrderStepCheck(sysOrderStep).checkNull("订单工序不存在");
        OrderStepBuilder orderBuilder = new OrderStepBuilder();
        orderBuilder.appendCode(code).appendEdit(loginUser).close();
        //关闭订单信息
        if (!prodOrderStepService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("关闭订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException("开启订单工序异常");
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, orderBuilder.getCode());
    }

    /**
     * 订单详情
     *
     * @param code 订单编码
     * @return Result
     */
    public Result<OrderStepVO> viewOrderStep(String code) {
        ValidateUtil.hasLength(code, "参数[code]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        ProdOrderStep sysOrderStep = prodOrderStepService.queryOrderStepByOrderStepCode(code, loginUser);
        new OrderStepCheck(sysOrderStep).checkNull("订单工序不存在");
        OrderStepVOBuilder orderStepBuilder = new OrderStepVOBuilder();
        orderStepBuilder.append(sysOrderStep);
        ProdStep step = prodStepService.queryStepByStepCode(sysOrderStep.getStepCode(), loginUser);
        orderStepBuilder.append(step);
        //查询仓库信息
        WmsWarehouse inWarehouse = wmsWarehouseService.queryWarehouseByWarehouseCode(sysOrderStep.getInWarehouseCode(), loginUser);
        orderStepBuilder.appendIn(inWarehouse);
        WmsWarehouse outWarehouse = wmsWarehouseService.queryWarehouseByWarehouseCode(sysOrderStep.getOutWarehouseCode(), loginUser);
        orderStepBuilder.appendOut(outWarehouse);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, orderStepBuilder.bulid());
    }

}
